import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Checkbox} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATETIME_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions, getUrl} from './utils';
import {injectIntl, language} from './intl';
import {conventEnumValueToString, formatDateTime} from '../utils';
import styles from './style.css';
import PartSaleOrderSelectPanel from './PartSaleOrderSelectPanel';
import SearchInput from 'Shared/components/SearchInput';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import {newOrderValidator} from './validator';
import {partSaleOrderQuery} from './api';
import {transportType, palletizing, cabinetType} from '../Enum';

const FormItem = Form.Item;
const cabinetTypeList = cabinetType.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showPartSaleOrderSelectPanel: false,
        details: []
    }
    componentDidMount() {
        const partSaleOrder = getUrl(this.props.history.location.search);
        if(partSaleOrder.partSaleOrderId)
            partSaleOrderQuery({id: partSaleOrder.partSaleOrderId})
                .then(res => {
                    if(res.ok) {
                        const row = res.data.content[0];
                        this.setState({
                            details: row.details,
                            data: {
                                partOrderId: row.id,
                                orderCode: row.code,
                                dealerCode: row.dealerCode,
                                dealerName: row.dealerName,
                                piCode: row.piCode,
                                partOrderTypeName: row.partOrderTypeName,
                                submitTime: row.submitTime,
                                transportType: row.transportType,
                                labelRequirement: row.labelRequirement,
                                shippingMark: row.shippingMark,
                                isSeparate: row.isSeparate,
                                palletizing: row.palletizing,
                                isEngine: false,
                                rowVersion: row.rowVersion
                            },
                            hasOperat: true
                        });
                    }
                });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    isEngineCheck = e => {
        const isEngine = e.target.checked;
        this.setState({
            data: Object.assign({}, this.state.data, {
                isEngine
            })
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSelectPartSaleOrder = records => {
        this.setState({
            details: records.details,
            data: {
                partOrderId: records.id,
                orderCode: records.code,
                dealerCode: records.dealerCode,
                dealerName: records.dealerName,
                piCode: records.piCode,
                partOrderTypeName: records.partOrderTypeName,
                submitTime: records.submitTime,
                transportType: records.transportType,
                labelRequirement: records.labelRequirement,
                shippingMark: records.shippingMark,
                isSeparate: records.isSeparate,
                palletizing: records.palletizing,
                isEngine: false,
                rowVersion: records.rowVersion
            },
            hasOperat: true,
            showPartSaleOrderSelectPanel: false
        });
    }
    onClickSearchBtn = () => {
        this.setState({showPartSaleOrderSelectPanel: true});
    }
    onClosePartSaleOrderSelectPanel = () => {
        this.setState({showPartSaleOrderSelectPanel: false});
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data} = this.state;
        const isValid = newOrderValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validateOrderCode = !data.partOrderId && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions);
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.planQuantity',
                defaultMessage: '订货数量'
            }),
            dataIndex: 'planQuantity'
        }, {
            title: formatMessage({
                id: 'newPanel.column.businessCheck',
                defaultMessage: '商检'
            }),
            dataIndex: 'businessCheck',
            render: text => text ? formatMessage({
                id: 'newPanel.column.yes',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'newPanel.column.no',
                defaultMessage: '否'
            })
        }, {
            title: formatMessage({
                id: 'newPanel.column.airMagneticCheck',
                defaultMessage: '空运磁检'
            }),
            dataIndex: 'airMagneticCheck',
            render: text => text ? formatMessage({
                id: 'newPanel.column.yes',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'newPanel.column.no',
                defaultMessage: '否'
            })
        }, {
            title: formatMessage({
                id: 'newPanel.column.dangerousGoods',
                defaultMessage: '空运危险'
            }),
            dataIndex: 'dangerousGoods',
            render: text => text ? formatMessage({
                id: 'newPanel.column.yes',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'newPanel.column.no',
                defaultMessage: '否'
            })
        }, {
            title: formatMessage({
                id: 'newPanel.column.chemicalCheck',
                defaultMessage: '化工鉴定'
            }),
            dataIndex: 'chemicalCheck',
            render: text => text ? formatMessage({
                id: 'newPanel.column.yes',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'newPanel.column.no',
                defaultMessage: '否'
            })
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '订单基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.orderCode',
                                        defaultMessage: '销售订单编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateOrderCode}
                                    required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.orderCode}
                                            onClickSearchBtn={this.onClickSearchBtn} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerName',
                                        defaultMessage: '总代名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.piCode',
                                        defaultMessage: 'PI编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.piCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partOrderTypeName',
                                        defaultMessage: '订单类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.partOrderTypeName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.submitTime',
                                            defaultMessage: '提报日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.submitTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.column.packing',
                        defaultMessage: '包装信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.transportType',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.transportType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.labelRequirement',
                                        defaultMessage: '标签要求'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.labelRequirement}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shippingMark',
                                        defaultMessage: '唛头要求'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.shippingMark}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.isSeparate',
                                        defaultMessage: '商检'
                                    })} {...FORM_OPTIONS.item}>
                                        <Checkbox
                                            disabled={true}
                                            checked={data.isSeparate}
                                            name="isSeparate"
                                            value={data.isSeparate}>
                                        </Checkbox>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.palletizing',
                                        defaultMessage: '托盘要求'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(palletizing, data.palletizing)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.isEngine',
                                        defaultMessage: '包含发动机'
                                    })} {...FORM_OPTIONS.item}>
                                        <Checkbox
                                            checked={data.isEngine}
                                            name="isEngine"
                                            value={data.isEngine}
                                            onChange={this.isEngineCheck}>
                                        </Checkbox>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.cabinetType',
                                        defaultMessage: '柜形'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="cabinetType"
                                            value={data.cabinetType}
                                            options={cabinetTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartSaleOrderSelectPanel &&
                        <PartSaleOrderSelectPanel
                            selectKey={data.id}
                            onCancel={this.onClosePartSaleOrderSelectPanel}
                            onSelect={this.onSelectPartSaleOrder} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    partSaleOrderId: PropTypes.string,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
